package com.gec.auction.controller;

import com.gec.auction.pojo.User;
import com.gec.auction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Irene_baebae
 * @version 1.0
 */
@Controller
public class UserController {
    @Autowired
    HttpSession session;
    @Autowired
    private UserService userService;
    @RequestMapping("/login.html")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/register.html")
    public String toRegister(){
        return "register";
    }
//    @RequestMapping(value = "/{page}")
//    public String page(@PathVariable String page){
//        return page;
//    }

    @RequestMapping("/doLogin")
    public String doLogin(String username,  //用户输入用户名
                          String userPassword, //用户输入密码
                          String valideCode, //用户输入验证码
                          Model model){
        //取出系统随机生成的验证码
        String vCode = (String)session.getAttribute("vrifyCode");
        System.out.println("vCode = " + vCode);
        //校验验证码正确性
       if(valideCode.equals(vCode)){
           System.out.println("验证码正确");
           User user = userService.doLogin(username,userPassword);
           if(user == null){
               model.addAttribute("errorMsg","账号密码错误");
               return "login";
           }else {
               session.setAttribute("user",user);
               System.out.println("登录成功");
               return "redirect:list";
        }
       }else{
           System.out.println("验证码错误");
           model.addAttribute("errorMsg","验证码错误");
           return "login";
       }
    }

    @RequestMapping("/registerUser")
    public String register(User user){
        user.setUserisadmin(0);  //默认1：普通用户，1：管理员用户
        userService.registerUser(user);
        System.out.println("注册成功");
        return "redirect:login.html";  //重定向到登录页面
    }
}
